package managedbean.CI.Position;

import entity.Position;
import entity.Role;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import session.stateless.PositionSessionBeanLocal;
import session.stateless.RoleSessionBeanLocal;

@ManagedBean(name="editPositionManagerBean")
@ViewScoped

public class EditPositionManagerBean implements Serializable
{
    @EJB
    private PositionSessionBeanLocal positionSessionBeanLocal;
    
    @EJB
    private RoleSessionBeanLocal roleSessionBeanLocal;
    
    private Position positionToEdit;
    private Role[] selectedRoles;
    private List<Role> roles;
    
    public Position getPositionToEdit() {
        return positionToEdit;
    }
    public void setPositionToEdit(Position positionToEdit) {
        this.positionToEdit = positionToEdit;
    }

    public Role[] getSelectedRoles() {
        return selectedRoles;
    }

    public void setSelectedRoles(Role[] selectedRoles) {
        this.selectedRoles = selectedRoles;
    }

    public List<Role> getRoles() {
        return roleSessionBeanLocal.getRoles();
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }
    
    public EditPositionManagerBean() {}
    
    public void initView(PhaseEvent event) throws IOException
    {
        if(this.positionToEdit == null)
        {             
            this.positionToEdit = (Position)FacesContext.getCurrentInstance().getExternalContext().getFlash().get("selectedPosition");    
        }
    }
    
    public void updateExistingPosition(ActionEvent event)
    {
        List<Role> temp_SelectedRoles = new ArrayList();
        for (Role role : this.getSelectedRoles()){
            temp_SelectedRoles.add(role);
        } 
        positionToEdit.setRoles(temp_SelectedRoles);
        System.out.println("********* " + positionToEdit.getDescription());
        positionSessionBeanLocal.updatePosition(positionToEdit.getId(), positionToEdit.getDescription(), positionToEdit.getRoles());
    }    
}
